package com.leetcode.algorithm.topic.stack;

import java.util.ArrayList;
import java.util.List;

/**
 * 155. 最小栈
设计一个支持 push，pop，top 操作，并能在常数时间内检索到最小元素的栈。

push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.
 * @author: jie.deng
 * @time: 2019年1月31日 上午12:43:56
 */
class MinStack {
	private List<Integer> list;
	private Integer min;
    /** initialize your data structure here. */
    public MinStack() {
		list = new ArrayList<Integer>();
    }
    
    public void push(int x) {
		list.add(x);
		if (min == null || x < min) {
			min = x;
		}
    }
    
	public void pop() {
		if (list == null || list.size() == 0) {
			return;
		}
		Integer val = list.remove(list.size() - 1);
		if (val.intValue() == min.intValue()) {
			min = null;
			for (Integer i : list) {
				if (min == null || min > i) {
					min = i;
				}
			}
		}
	}
    
    public int top() {
		if (list != null && list.size() != 0) {
			Integer val = list.get(list.size() - 1);
			return val;
		}
		return Integer.MIN_VALUE;
    }
    
    public int getMin() {
		return min == null ? Integer.MIN_VALUE : min;
    }
    
    public static void main(String[] args) {
    	MinStack minStack = new MinStack();
    	minStack.push(512);
    	minStack.push(-1024);
    	minStack.push(-1024);
    	minStack.push(512);
    	minStack.pop();
    	minStack.getMin();
    	minStack.pop();
    	minStack.getMin();
    	minStack.pop();   
    	int min = minStack.getMin();
    	System.out.println(min);
	}
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */